from threading import Thread, RLock
import time

class Clock(Thread):

    def __init__(self, delay_ms = 500):
        Thread.__init__(self)
        self.__lock = RLock()
        self.__is_stop = False
        self.__delay = delay_ms / 1000.0
        self.__listeners = []

    def run(self):
        self.__is_stop = False
        while(not self.__is_stop):
            with self.__lock:
                for listener in self.listeners:
                    listener.tick(time.time())
            time.sleep(self.__delay)

    def add_listener(self, listener):
        self.listeners.append(listener)
        
    def stop(self):
        with self.__lock:
            self.__is_stop = True
            self.reset_listeners()

    def reset_listeners(self):
        with self.__lock:
            self.__listeners = []
            time.sleep(self.__delay)

    @property
    def listeners(self):
        return self.__listeners

    @property
    def delay_ms(self):
        return self.__delay * 1000

    @delay_ms.setter 
    def delay_ms(self, value):
        self.__delay = value / 1000.0




